<template>
  <div class="tab-view">
    <div class="header-top">
      <a-button type="dashed" shape="circle" :icon="h(ReloadOutlined)" @click="reloadFn" />
      <a-input-search v-model:value="inputUrl" placeholder="url" enter-button="go" spellcheck="false" @search="onSearch" />
    </div>
    <div class="content">
      <webview ref="webRef" src="about:blank" class="webview" allowpopups></webview>
    </div>
  </div>
</template>
<script setup lang="ts">
import { h, ref, onMounted } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'

const emit = defineEmits(['newTag'])
const props = defineProps({
  url: {
    type: String,
    default: ''
  }
})
const webRef = ref<any>()
const currentUrl = ref(props.url)
const inputUrl = ref(currentUrl.value)

onMounted(() => {
  const el = webRef.value
  let isOne = true
  el.addEventListener('dom-ready', () => {
    if (isOne && currentUrl.value) {
      isOne = false
      el.loadURL(currentUrl.value)
    }
  })

  el.addEventListener('load-commit', (_e) => {
    // inputUrl.value = e.target.src
  })
  el.addEventListener('context-menu', (e) => {
    e.preventDefault()
    console.log(e)
    if (!el.isDevToolsOpened()) {
      el.openDevTools()
    }
  })

  // el.addEventListener('will-navigate', (e) => {
  //   console.log('will-navigate', e)
  //   // const webContents = el.getWebContents()
  //   // webContents.on('new-window', (e, url) => {
  //   //   console.log('new', url)
  //   // })
  // })
})

function onSearch() {
  const el = webRef.value
  let url = inputUrl.value
  // 判断是否是http开头的url
  if (!url.startsWith('http')) {
    url = `http://${url}`
  }
  el.loadURL(url)
  // ....
}

function reloadFn() {
  const el = webRef.value
  el.reload()
}
</script>
<style scoped lang="scss">
.tab-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  .header-top {
    flex: none;
    display: flex;
  }
  .content {
    flex: auto;
  }
}

.webview {
  height: 100%;
}
</style>
